import fs from 'node:fs';
import path from 'node:path';
import { CONFIG } from '../config.js';

function ensureDir(dir: string) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

function logFilePath(): string {
  const now = new Date();
  const y = now.getUTCFullYear();
  const m = String(now.getUTCMonth() + 1).padStart(2, '0');
  const d = String(now.getUTCDate()).padStart(2, '0');
  const dir = path.join(CONFIG.STORAGE.LOG_DIR, 'daily');
  ensureDir(dir);
  return path.join(dir, `${y}-${m}-${d}.log`);
}

function write(line: string) {
  try {
    fs.appendFileSync(logFilePath(), `${new Date().toISOString()} ${line}\n`, 'utf-8');
  } catch {}
}

export function logInfo(msg: string) { write(`[INFO] ${msg}`); }
export function logWarn(msg: string) { write(`[WARN] ${msg}`); }
export function logError(msg: string) { write(`[ERROR] ${msg}`); }

export function logProgress(scope: string, processed: number, total?: number) {
  const t = total !== undefined ? `/${total}` : '';
  write(`[PROGRESS] ${scope} ${processed}${t}`);
}

export function readLog(date?: string): string {
  // date format YYYY-MM-DD, default today
  const now = new Date();
  const [y, m, d] = date ? date.split('-') : [String(now.getUTCFullYear()), String(now.getUTCMonth() + 1).padStart(2, '0'), String(now.getUTCDate()).padStart(2, '0')];
  const fp = path.join(CONFIG.STORAGE.LOG_DIR, 'daily', `${y}-${m}-${d}.log`);
  if (fs.existsSync(fp)) return fs.readFileSync(fp, 'utf-8');
  return '';
}